package com.example.lishucheng.activites;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.util.Patterns;
import android.view.View;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.example.lishucheng.databinding.ActivitySignInBinding;
import com.example.lishucheng.utilities.Constants;
import com.example.lishucheng.utilities.PreferenceManager;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;

public class SignInActivity extends AppCompatActivity {

    private ActivitySignInBinding binding;
    private PreferenceManager preferenceManager;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        preferenceManager = new PreferenceManager(getApplicationContext());
        if (preferenceManager.getBoolean(Constants.KEY_IS_SIGNED_IN)){
            Intent intent = new Intent(getApplicationContext(),MainActivity.class);
            startActivity(intent);
            finish();
        }
        binding = ActivitySignInBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        setListeners();
//        EdgeToEdge.enable(this);
//        setContentView(R.layout.activity_sign_in);
//        // 边衬区适配代码...
//        // 绑定跳转到 SignInActivity 的 TextView
//        TextView textSignIn = findViewById(R.id.textCreateNewAccount);
//        textSignIn.setOnClickListener(v -> {
//            // 跳转到 SignInActivity
//            startActivity(new Intent(SigninActivity.this, SignUpActivity.class));
//        });
//        Button SingIn = findViewById(R.id.buttonSigIn); // 确保布局文件存在该ID



//        SingIn.setOnClickListener(v -> addDataToFirestore());
    }
    private void setListeners() {
        binding.textCreateNewAccount.setOnClickListener(v ->
                startActivity(new Intent(getApplicationContext(),SignUpActivity.class)));
        binding.buttonSignIn.setOnClickListener(v ->{
            if (isValidSignInDetails()){
                signIn();
            }
        });
    }

//    private void addDataToFirestore(){
//        FirebaseFirestore database = FirebaseFirestore.getInstance();
//        HashMap<String, Objects> data = new HashMap<>();
//        data.put("first_name", "");
//        data.put("last_name" , "JACK");
//        database.collection("user")
//                .add(data)
//                .addOnSuccessListener(documentReference -> {
//                    Toast.makeText(getApplicationContext(),"Data Inserted",Toast.LENGTH_SHORT).show();
//                })
//                .addOnFailureListener(e -> {
//                    Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
//                });
//    }
// 修正后的数据库操作方法
//private void addDataToFirestore() {
//    FirebaseFirestore database = FirebaseFirestore.getInstance();
//    HashMap<String, Object> userData = new HashMap<>();
//    userData.put("first_name", "John");  // 修正参数类型为Object
//    userData.put("last_name", "Doe");
//
//    database.collection("users")  // 建议集合名用复数形式[6](@ref)
//            .add(userData)
//            .addOnSuccessListener(documentReference -> {
//                Toast.makeText(this, "用户ID: " + documentReference.getId(),
//                        Toast.LENGTH_SHORT).show();
//            })
//            .addOnFailureListener(e -> {
//                Log.e("FirestoreError", "写入失败: ", e);  // 增加日志追踪[6](@ref)
//                Toast.makeText(this, "错误: " + e.getLocalizedMessage(),
//                        Toast.LENGTH_LONG).show();
//            });
//}
    private void signIn(){
        loading(true);
        FirebaseFirestore database = FirebaseFirestore.getInstance();
        database.collection(Constants.KEY_COLLECTION_USERS)
                .whereEqualTo(Constants.KEY_EMAIL,binding.inputEmail.getText().toString())
                .whereEqualTo(Constants.KEY_PASSWORD,binding.inputPassword.getText().toString())
                .get()
                .addOnCompleteListener(task -> {
                    if (task.isSuccessful() && task.getResult() != null
                            && task.getResult().getDocuments().size() > 0) {
                        DocumentSnapshot documentSnapshot = task.getResult().getDocuments().get(0);
                        preferenceManager.putBoolean(Constants.KEY_IS_SIGNED_IN,true);
                        preferenceManager.putString(Constants.KEY_USER_ID,documentSnapshot.getId());
                        preferenceManager.putString(Constants.KEY_NAME,documentSnapshot.getString(Constants.KEY_NAME));
                        preferenceManager.putString(Constants.KEY_IMAGE,documentSnapshot.getString(Constants.KEY_IMAGE));
                        Intent intent = new Intent(getApplicationContext(),MainActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                        startActivity(intent);
                    }else {
                        loading(false);
                        showToast("Unable to sign in");
                    }
                });
    }

    private void loading(Boolean isLoading){
        if (isLoading){
            binding.buttonSignIn.setVisibility(View.INVISIBLE);
            binding.progressBar.setVisibility(View.VISIBLE);
        }else {
            binding.progressBar.setVisibility(View.INVISIBLE);
            binding.buttonSignIn.setVisibility(View.VISIBLE);
        }
    }
    private void showToast(String message){
        Toast.makeText(getApplicationContext(),message, Toast.LENGTH_SHORT).show();
    }

    private Boolean isValidSignInDetails(){
        if(binding.inputEmail.getText().toString().trim().isEmpty()){
            showToast("Enter email");
            return false;
        }else if (!Patterns.EMAIL_ADDRESS.matcher(binding.inputEmail.getText().toString()).matches()){
            showToast("Enter valid email");
            return true;
        } else if (binding.inputPassword.getText().toString().trim().isEmpty()) {
            showToast("Enter password");
            return false;
        }else {
        return true;
        }
    }
}